/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package utilitaires.ftp;

import java.io.*;
import java.util.Properties;
import org.apache.commons.net.ftp.*;

/**
 *
 * @author Fred
 */
public final class FTPTransfer {

    private static final FTPClient FTP = new FTPClient();
    private static final Properties PROPERTIES = new Properties();
    private static InputStream INPUT_STREAM;

    public static void connect() throws Exception {
        if (!FTP.isConnected()) {
            loadProperties();
            FTP.connect(PROPERTIES.getProperty("server"));
            if (!FTPReply.isPositiveCompletion(FTP.getReplyCode())) {
                FTP.disconnect();
                throw new Exception("Impossible de se connecter au serveur FTP.");
            }
            FTP.login(PROPERTIES.getProperty("login"), PROPERTIES.getProperty("password"));
            FTP.setFileType(FTPClient.BINARY_FILE_TYPE);
            FTP.enterLocalPassiveMode();
            closeProperties();
        }
    }

    public static void uploadFile(InputStream file, String hostFileFullName) throws Exception {
        FTP.storeFile(hostFileFullName, file);
    }

    public static boolean downloadFile(String hostFileFullName, File localFile) throws IOException {
        boolean resultat;
        try (OutputStream ops = new BufferedOutputStream(new FileOutputStream(localFile))) {
            resultat = FTP.retrieveFile(hostFileFullName, ops);
        }
        return resultat;
    }

    public static void removeFile(String hostFileFullName) throws IOException {
        FTP.deleteFile(hostFileFullName);
    }

    public static void disconnect() {
        if (FTP.isConnected()) {
            try {
                FTP.logout();
                FTP.disconnect();
            } catch (IOException ex) {

            }
        }
    }

    private static void loadProperties() throws IOException {        
        INPUT_STREAM = FTPTransfer.class.getClassLoader().getResourceAsStream("ftp.properties");
        PROPERTIES.load(INPUT_STREAM);
    }

    private static void closeProperties() throws IOException {
        INPUT_STREAM.close();
    }
}
